package com.sz.stock.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;


/**
 * JwtUtils: Jwt工具类
 * 用于生成签证和解析签证
 */
public class JwtUtils {

    private static String id = "stockUser";
    private static long ttl = 600000;       //设置token有效时间为10分钟；

    //生成token
    public static String createToken(String subject,String roles){
        long time = System.currentTimeMillis();     //保存系统当前时间；
        Date beginTime = new Date(time);
        Date endTime = new Date(time + ttl);

        JwtBuilder token = Jwts.builder().setId(id).setIssuedAt(beginTime).setExpiration(endTime)
                .setSubject(subject).signWith(SignatureAlgorithm.HS256,id).claim("roles",roles);
        return token.compact();
    }

    //解析token
    public static Claims parseToken(String token){
        Claims claims = Jwts.parser().setSigningKey(id).parseClaimsJws(token).getBody();
        System.out.println(claims.getId());
        System.out.println(claims.getSubject());
        System.out.println(claims.getIssuedAt());
        System.out.println(claims.getExpiration());
        System.out.println(claims.get("roles"));
        return claims;
    }

}
























